package com.etoak.web.sys_user.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.etoak.utils.ResultUtils;
import com.etoak.utils.ResultVo;
import com.etoak.web.sys_menu.entity.AssignTreeParm;
import com.etoak.web.sys_menu.entity.AssignTreeVo;
import com.etoak.web.sys_menu.entity.SysMenu;
import com.etoak.web.sys_menu.service.SysMenuService;
import com.etoak.web.sys_role_user.entity.SysUserRole;
import com.etoak.web.sys_role_user.service.SysUserRoleService;
import com.etoak.web.sys_user.entity.SysUser;
import com.etoak.web.sys_user.entity.SysUserParam;
import com.etoak.web.sys_user.entity.UpdatePassword;
import com.etoak.web.sys_user.entity.UserInfo;
import com.etoak.web.sys_user.service.SysUserService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Author by 孙有泽
 * @Date 2025/2/18 12:54
 * @Description
 */
@RequestMapping("/api/user")
@RestController
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @PreAuthorize("hasAnyAuthority('sys:user:add')")
    @PostMapping("/add")
    public ResultVo add(@RequestBody SysUser sysUser){
        sysUser.setPassword(bCryptPasswordEncoder.encode(sysUser.getPassword()));
        sysUserService.saveUser(sysUser);
        return ResultUtils.success("添加成功");
    }
    @PreAuthorize("hasAnyAuthority('sys:user:edit')")
    @PutMapping("/update")
    public ResultVo update(@RequestBody SysUser sysUser){
      sysUserService.updateUser(sysUser);
        return ResultUtils.success("修改成功");
    }
    @PreAuthorize("hasAnyAuthority('sys:user:delete')")
    @DeleteMapping("/{id}")
    public ResultVo delete(@PathVariable String id){
        sysUserService.deleteUser(id);
        return ResultUtils.success("删除成功");
    }
    @GetMapping("/getList")
    public ResultVo list(SysUserParam sysUserParam){
        Page<SysUser> objectPage = new Page<>(sysUserParam.getCurrentPage(), sysUserParam.getPageSize());
        QueryWrapper<SysUser> objectQueryWrapper = new QueryWrapper<>();
        if(StringUtils.isNotEmpty(sysUserParam.getNickname())) {
            objectQueryWrapper.lambda().like(SysUser::getNickname, sysUserParam.getNickname());
        }
        if(StringUtils.isNotEmpty(sysUserParam.getPhone())) {
            objectQueryWrapper.lambda().like(SysUser::getPhone, sysUserParam.getPhone());
        }
        objectQueryWrapper.lambda().orderByDesc(SysUser::getCreateTime);
        Page<SysUser> page = sysUserService.page(objectPage, objectQueryWrapper);
        return ResultUtils.success("查询成功",page);

    }

    //根据用户id查询用户的角色
    @GetMapping("/getRoleList")
    public ResultVo getRoleListByUserId(String userId){
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysUserRole::getUserId,userId);
        List<SysUserRole> list = sysUserRoleService.list(queryWrapper);
        ArrayList<String> roleList = new ArrayList<>();
        Optional.ofNullable(list).orElse(new ArrayList<>()).forEach(item->{roleList.add((item.getRoleId()));});
        return ResultUtils.success("查询成功",roleList);

    }
    @PostMapping("/resetPassword")
    public ResultVo resetPassword(@RequestBody SysUser sysUser){
        UpdateWrapper<SysUser> objectUpdateWrapper = new UpdateWrapper<>();
        objectUpdateWrapper.lambda().eq(SysUser::getId,sysUser.getId())
                .set(SysUser::getPassword,bCryptPasswordEncoder.encode("666666"));
        if(sysUserService.update((objectUpdateWrapper))){
            return ResultUtils.success("重置密码成功");
        }
        return ResultUtils.error("重置密码失败");

    }
    @GetMapping("/getAssingTree")
    public ResultVo getAssingTree(AssignTreeParm parms){
        AssignTreeVo assignTree = sysUserService.getAssignTree(parms);
        return ResultUtils.success("查询成功",assignTree);

    }
    @PostMapping("/updataPassword")
    public ResultVo updatePassword(@RequestBody UpdatePassword updatePassword){
        SysUser byId = sysUserService.getById(updatePassword.getId());
       /* if(!updatePassword.getOldPassword().equals(byId.getPassword())){
            return ResultUtils.error("原密码不正确");
        }*/
        if(bCryptPasswordEncoder.matches(updatePassword.getOldPassword(),byId.getPassword())){
            return ResultUtils.error("原密码不正确");
        }
        UpdateWrapper<SysUser> objectUpdateWrapper = new UpdateWrapper<>();
        objectUpdateWrapper.lambda().set(SysUser::getPassword,bCryptPasswordEncoder.encode(updatePassword.getNewPassword())).eq(SysUser::getId,updatePassword.getId());
        if(sysUserService.update(objectUpdateWrapper)){
            return ResultUtils.success("修改密码成功");
        }
        return ResultUtils.error("修改密码失败");


    }
    @GetMapping("/getInfo")
    public ResultVo  getInfo(String id){
        SysUser byId = sysUserService.getById(id);
        List<SysMenu> menuList=null;
        if(StringUtils.isNotEmpty(byId.getIsadmin()+"")&&"0".equals(byId.getIsadmin()+"")){
            menuList= sysMenuService.list();
        }else{
            menuList=sysMenuService.queryMenuByUserId(byId.getId());
        }
        List<String> collect = Optional.ofNullable(menuList).orElse(new ArrayList<>()).stream().
                filter(item -> StringUtils.isNotEmpty(item.getCode())).
                map(item -> item.getCode()).
                collect(Collectors.toList());
        UserInfo userInfo = new UserInfo();
        userInfo.setName(byId.getNickname());
        userInfo.setId(byId.getId());
        userInfo.setPermissions(collect.toArray());
        return ResultUtils.success("查询成功",userInfo);
    }
}
